package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.enums.BrandImgTypeEnum;
import com.ytjj.qmyx.supplychain.common.enums.BrandStatusEnum;
import com.ytjj.qmyx.supplychain.common.model.BankerBrandImgVO;
import com.ytjj.qmyx.supplychain.common.model.BankerBrandVO;
import com.ytjj.qmyx.supplychain.common.model.dto.WaitBuildOldDto;
import com.ytjj.qmyx.supplychain.common.model.request.*;
import com.ytjj.qmyx.supplychain.common.model.response.*;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RefreshScope
public class BankerBrandService extends AbstractService<BankerBrandMapper, YxBankerBrand> {
    @Resource
    private BankerInfoMapper bankerInfoMapper;
    @Resource
    private BankerBrandMapper bankerBrandMapper;
    @Resource
    private BankerMessageMapper bankerMessageMapper;
    @Resource
    private ProductCategoryMapper productCategoryMapper;
    @Resource
    private BankerBrandImgMapper bankerBrandImgMapper;
    @Autowired
    private BankerService bankerService;
    @Autowired
    private BankerInfoService bankerInfoService;
    @Autowired
    private BankerBrandImgService bankerBrandImgService;
    @Autowired
    private BankerSiteService bankerSiteService;
    @Autowired
    private BankerProductService bankerProductService;
    @Value(value = "${history-off:true}")
    private boolean historyOff;

    public YxBankerBrand selectByBankerIdAndFistTime(Integer bankerId, Integer firstTime) {
        Example example = new Example(YxBankerBrand.class);
        example.createCriteria().andEqualTo("bankerId", bankerId).andEqualTo("firstTime", firstTime);
        example.setOrderByClause("create_time desc limit 1");
        YxBankerBrand bankerBrand = bankerBrandMapper.selectOneByExample(example);
        return bankerBrand;
    }

    public CommonResult save(BankerInfoRequest bankerInfoRequest) {
        log.info("供应商保存三步曲参数：{}", bankerInfoRequest);
        Integer bankerId = bankerService.getUserInfo().getId();
        YxBankerInfo oldBankerInfo = new YxBankerInfo();
        oldBankerInfo.setBankerId(bankerId);

        YxBanker userInfo = bankerService.getUserInfo();
        bankerInfoRequest.setBankerName(userInfo.getName());
        bankerInfoRequest.setBankerId(bankerId);
        bankerInfoRequest.setCreateTime(new Date());
        int count = 0;
        if (null != bankerInfoRequest.getInfoId()) {
            YxBankerInfo yxBankerInfo = buildYxBankerInfo(bankerInfoRequest);
            if (null != yxBankerInfo) {
                count = bankerInfoMapper.updateByPrimaryKeySelective(yxBankerInfo);
            }
        }else {
            count = bankerInfoMapper.insertSelective(buildYxBankerInfo(bankerInfoRequest));
        }

        YxBankerSite bankerSite = buildYxBankerSite(bankerInfoRequest);
        if (null != bankerSite && !BrandStatusEnum.PASS.getCode().equals(bankerSite.getCheckStatus())) {
            count = bankerSiteService.syncSite(bankerSite);
        }
        YxBankerBrand yxBankerBrand = null;
        try {
            bankerInfoRequest.getBankerBrandRequest().setBankerSiteId(bankerSite.getId());
            yxBankerBrand = buildYxBankerBrand(bankerInfoRequest);
            if (null != yxBankerBrand) {
                yxBankerBrand.setFirstTime(1);
                if (null != yxBankerBrand.getId()) {
                    count = bankerBrandMapper.updateByPrimaryKeySelective(yxBankerBrand);
                }else {
                    count = bankerBrandMapper.insertSelective(yxBankerBrand);
                }
            }else{
                log.warn("===品牌信息已经存在并且审核通过了，不能重复提交品牌信息===");
                return CommonResult.success();
            }
        } catch (ParseException e) {
            log.error("品牌信息保存失败，{}", e);
            return CommonResult.failed("品牌信息保存失败");
        }
        if (null != bankerInfoRequest.getBankerBrandRequest().getBrandId()) {
            log.info("===bankerInfoRequest.getBankerBrandRequest().getBrandId()==={}", bankerInfoRequest.getBankerBrandRequest().getBrandId());
            Example example = new Example(YxBankerBrandImg.class);
            example.createCriteria().andEqualTo("bankerBrandId", bankerInfoRequest.getBankerBrandRequest().getBrandId());
            bankerBrandImgService.deleteByExample(example);
        }
        log.info("===bankerInfoRequest==={}", bankerInfoRequest);
        log.info("===yxBankerBrand.getId()==={}", yxBankerBrand.getId());
        List<YxBankerBrandImg> waitSaveList = buildYxBankerBrandImg(bankerInfoRequest, yxBankerBrand.getId());
        boolean result = bankerBrandImgService.insertBatch(waitSaveList);
        return CommonResult.success();
    }

    private YxBankerInfo buildYxBankerInfo(BankerInfoRequest bankerInfoRequest) {
        YxBankerInfo yxBankerInfo = new YxBankerInfo();
        if (null != bankerInfoRequest.getInfoId()) {
            yxBankerInfo = bankerInfoService.selectByBankerId(bankerInfoRequest.getBankerId());
            if (null != yxBankerInfo && 2 == yxBankerInfo.getStatus()) {
                return null;
            }
        }
        yxBankerInfo.setBankerId(bankerInfoRequest.getBankerId());
        yxBankerInfo.setBankerName(bankerInfoRequest.getBankerName());
        yxBankerInfo.setCompanyName(bankerInfoRequest.getCompanyName());
        yxBankerInfo.setCompanyAddress(bankerInfoRequest.getCompanyAddress());
        yxBankerInfo.setCompanyTel(bankerInfoRequest.getCompanyTel());
        yxBankerInfo.setBusinessLicense(bankerInfoRequest.getBusinessLicense());
        yxBankerInfo.setBusinessLicenseImg(bankerInfoRequest.getBusinessLicenseImg());
        yxBankerInfo.setForver(bankerInfoRequest.getForver());
        if (bankerInfoRequest.getForver()==1) {
            yxBankerInfo.setBusinessLimitStart(null);
            yxBankerInfo.setBusinessLimitEnd(null);
        }else {
            yxBankerInfo.setBusinessLimitStart(bankerInfoRequest.getBusinessLimitStart());
            yxBankerInfo.setBusinessLimitEnd(bankerInfoRequest.getBusinessLimitEnd());
        }
        yxBankerInfo.setHostName(bankerInfoRequest.getHostName());
        yxBankerInfo.setIdCard(bankerInfoRequest.getIdCard());
        yxBankerInfo.setCardImgFront(bankerInfoRequest.getCardImgFront());
        yxBankerInfo.setCardImgBehind(bankerInfoRequest.getCardImgBehind());
        yxBankerInfo.setBankHouse(bankerInfoRequest.getBankHouse());
        yxBankerInfo.setCreditCardNumbers(bankerInfoRequest.getCreditCardNumbers());
        yxBankerInfo.setStatus(1);
        if (null == bankerInfoRequest.getInfoId()) {
            yxBankerInfo.setCreateTime(new Date());
            yxBankerInfo.setReleased(0);
        }
        yxBankerInfo.setOpeningLicenseImg(bankerInfoRequest.getOpeningLicenseImg());
        return yxBankerInfo;
    }

    private YxBankerBrand buildYxBankerBrand(BankerInfoRequest bankerInfoRequest) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        YxBankerBrand yxBankerBrand = null;
        if (null != bankerInfoRequest.getBankerBrandRequest().getBrandId()) {
            yxBankerBrand = selectByPrimaryKey(bankerInfoRequest.getBankerBrandRequest().getBrandId());
            if (null != yxBankerBrand && BrandStatusEnum.PASS.getCode().equals(yxBankerBrand.getStatus())) {
                return yxBankerBrand;
            }
        }else {
            yxBankerBrand = new YxBankerBrand();
            yxBankerBrand.setReleased(0);
            yxBankerBrand.setPutOn(0);
        }
        yxBankerBrand.setBankerId(bankerInfoRequest.getBankerId());
        yxBankerBrand.setBankerSiteId(bankerInfoRequest.getBankerBrandRequest().getBankerSiteId());
        yxBankerBrand.setBrandType(bankerInfoRequest.getBankerBrandRequest().getBrandType());
        yxBankerBrand.setCategoryId(bankerInfoRequest.getBankerBrandRequest().getCategoryId());
        yxBankerBrand.setBrandName(bankerInfoRequest.getBankerBrandRequest().getBrandName());
        yxBankerBrand.setBrandLimitStart(null == bankerInfoRequest.getBankerBrandRequest().getBrandLimitStart() ? null : sdf.parse(bankerInfoRequest.getBankerBrandRequest().getBrandLimitStart()));
        yxBankerBrand.setBrandLimitEnd(null == bankerInfoRequest.getBankerBrandRequest().getBrandLimitEnd() ? null : sdf.parse(bankerInfoRequest.getBankerBrandRequest().getBrandLimitEnd()));
        yxBankerBrand.setAuthorizationStartTime(null == bankerInfoRequest.getBankerBrandRequest().getAuthorizationStartTime() ? null : sdf.parse(bankerInfoRequest.getBankerBrandRequest().getAuthorizationStartTime()));
        yxBankerBrand.setAuthorizationEndTime(null == bankerInfoRequest.getBankerBrandRequest().getAuthorizationEndTime() ? null : sdf.parse(bankerInfoRequest.getBankerBrandRequest().getAuthorizationEndTime()));
        yxBankerBrand.setAuthorizationType(bankerInfoRequest.getBankerBrandRequest().getAuthorizationType());
        yxBankerBrand.setStatus(BrandStatusEnum.WAIT_CHECK.getCode());
        return yxBankerBrand;
    }

    private YxBankerSite buildYxBankerSite(BankerInfoRequest bankerInfoRequest) {
        YxBankerSite yxBankerSite = new YxBankerSite();
        if (null != bankerInfoRequest.getSiteId()) {
            yxBankerSite = bankerSiteService.selectByPrimaryKey(bankerInfoRequest.getSiteId());
            if (null != yxBankerSite && BrandStatusEnum.PASS.getCode().equals(yxBankerSite.getCheckStatus())) {
                return yxBankerSite;
            }
        }
        yxBankerSite.setBankerId(bankerInfoRequest.getBankerId());
        yxBankerSite.setTitle(bankerInfoRequest.getTitle());
        yxBankerSite.setLongTitle(bankerInfoRequest.getLongTitle());
        yxBankerSite.setBrandStory(bankerInfoRequest.getBrandStory());
        yxBankerSite.setLogo(bankerInfoRequest.getLogo());
        yxBankerSite.setBgImg(bankerInfoRequest.getBgImg());
        yxBankerSite.setShareImg(bankerInfoRequest.getShareImg());
        yxBankerSite.setShareCopywrite(bankerInfoRequest.getShareCopywrite());
        if (null == bankerInfoRequest.getSiteId()) {
            yxBankerSite.setReleased(0);
        }
        return yxBankerSite;
    }

    private List<YxBankerBrandImg> buildYxBankerBrandImg(BankerInfoRequest bankerInfoRequest, Integer bankerBrandId) {
        List<BankerBrandImgRequest> registImgs = bankerInfoRequest.getBankerBrandRequest().getRegistImgs();
        List<BankerBrandImgRequest> licensImgs = bankerInfoRequest.getBankerBrandRequest().getLicensImgs();
        List<BankerBrandImgRequest> relImgs = bankerInfoRequest.getBankerBrandRequest().getRelImgs();

        List<YxBankerBrandImg> waitSaveList = new ArrayList<>();
        registImgs.stream().forEach(regist -> {
            YxBankerBrandImg bankerBrandImg = YxBankerBrandImg.builder()
                    .type(BrandImgTypeEnum.REGIST.getCode())
                    .bankerBrandId(bankerBrandId)
                    .imgUrl(regist.getImgUrl())
                    .sort(regist.getSort())
                    .createTime(new Date())
                    .build();
            waitSaveList.add(bankerBrandImg);
        });
        licensImgs.stream().forEach(regist -> {
            YxBankerBrandImg bankerBrandImg = YxBankerBrandImg.builder()
                    .type(BrandImgTypeEnum.LICENS.getCode())
                    .bankerBrandId(bankerBrandId)
                    .imgUrl(regist.getImgUrl())
                    .sort(regist.getSort())
                    .createTime(new Date())
                    .build();
            waitSaveList.add(bankerBrandImg);
        });
        if (!ObjectUtils.isEmpty(relImgs)) {
            relImgs.stream().forEach(regist -> {
                YxBankerBrandImg bankerBrandImg = YxBankerBrandImg.builder()
                        .type(BrandImgTypeEnum.REL.getCode())
                        .bankerBrandId(bankerBrandId)
                        .imgUrl(regist.getImgUrl())
                        .sort(regist.getSort())
                        .createTime(new Date())
                        .build();
                waitSaveList.add(bankerBrandImg);
            });
        }
        return waitSaveList;
    }


    /**
     * 更新供应商下面品牌未绑定店铺的数据
     * @param bankerId
     * @param bankerSiteId
     * @return
     */
    public CommonResult doUpdateBrandBankerSiteIdIsNullData(Integer bankerId, Integer bankerSiteId) {
        Example example = new Example(YxBankerBrand.class);
        example.createCriteria().andEqualTo("bankerId", bankerId)
                .andIsNull("bankerSiteId");
        List<YxBankerBrand> brands = selectByExample(example);
        brands.stream().forEach(s -> {
            s.setBankerSiteId(bankerSiteId);
        });
        updateBatchByPrimaryKeySelective(brands);
        return CommonResult.success();
    }

    public CommonResult checkStatus(BankerCheckStatusRequest request) {
        log.info("供应商品牌审核参数：{}", request);
        YxBankerBrand bankerBrand = selectByPrimaryKey(request.getId());
        if (null == bankerBrand) {
            return CommonResult.failed("找不到对应的品牌信息");
        }
        if (!bankerBrand.getStatus().equals(BrandStatusEnum.WAIT_CHECK.getCode())) {
            return CommonResult.failed("该品牌已审核，不能重复审核");
        }

//        YxBankerSite bankerSite = bankerSiteService.selectByPrimaryKey(bankerBrand.getBankerSiteId());
//        if (null == bankerSite) {
//            return CommonResult.failed("找不到供应商店铺信息");
//        }
//        if (bankerSite.getCheckStatus().equals(BrandStatusEnum.WAIT_CHECK.getCode())) {
//            return CommonResult.failed("该品牌对应的店铺信息未审核");
//        }

        Example example = new Example(YxBankerInfo.class);
        example.createCriteria().andEqualTo("bankerId", bankerBrand.getBankerId());
        YxBankerInfo bankerInfo = bankerInfoMapper.selectOneByExample(example);
        if (null == bankerInfo) {
            return CommonResult.failed("找不到供应商对应的主体信息");
        }
        if (bankerInfo.getStatus() == 1) {
            return CommonResult.failed("供应商对应的主体信息未审核");
        }
        bankerBrand.setStatus(request.getStatus());
        bankerBrand.setCheckMsg(request.getMsg());
        if (BrandStatusEnum.PASS.getCode().equals(request.getStatus())) {
            bankerBrand.setReleased(0);
            bankerBrand.setPutOn(1);
        }
        int count = updateByPrimaryKeySelective(bankerBrand);
        if (count <= 0) {
            return CommonResult.failed("审核失败");
        }
        if (count > 0) {
            YxBankerMessage message = new YxBankerMessage();
            message.setBankerId(bankerInfo.getBankerId());
            message.setBankerName(bankerInfo.getBankerName());
            message.setRemarks("您上传的商家品牌信息：" + bankerInfo.getBankerName() + (request.getStatus() == 1 ? " 已通过审核！" : "未通过审核,原因:" + request.getMsg()));
            message.setStatus(0);
            message.setType(request.getStatus() == 1 ? 5 : 6);
            message.setCreateTime(new Date());
            bankerMessageMapper.insertSelective(message);
        }
        return CommonResult.success("审核成功");
    }

    @Transactional
    public CommonResult singleSave(BankerBrandRequest request) {
        log.info("单笔新增品牌信息参数：{}", request);
        try {
            Integer bankerId = bankerService.getUserInfo().getId();

            Example example_bankerInfo = new Example(YxBankerInfo.class);
            Example.Criteria criteria_bankerInfo = example_bankerInfo.createCriteria();
            criteria_bankerInfo.andEqualTo("bankerId", bankerId);
            criteria_bankerInfo.andEqualTo("status", 2);
            YxBankerInfo bankerInfo = bankerInfoMapper.selectOneByExample(example_bankerInfo);
            if (null == bankerInfo) {
                return CommonResult.failed("请完善供应商主体信息");
            }

            Example example = new Example(YxBankerSite.class);
            Example.Criteria criteria_siteInfo = example.createCriteria();
            criteria_siteInfo.andEqualTo("bankerId", bankerId);
            criteria_siteInfo.andEqualTo("checkStatus", BrandStatusEnum.PASS.getCode());
            YxBankerSite bankerSite = bankerSiteService.selectOneByExample(example);
            if (null == bankerSite) {
                return CommonResult.failed("请完善供应商店铺信息");
            }
            BankerInfoRequest bankerInfoRequest = new BankerInfoRequest();
            bankerInfoRequest.setBankerId(bankerId);
            request.setBankerSiteId(bankerSite.getId());
            bankerInfoRequest.setBankerBrandRequest(request);
            YxBankerBrand bankerBrand = buildYxBankerBrand(bankerInfoRequest);
            bankerBrand.setFirstTime(0);
            int count = bankerBrandMapper.insertSelective(bankerBrand);
            if (count <= 0) {
                return CommonResult.failed("新增失败");
            }
            List<YxBankerBrandImg> waitSaveList = buildYxBankerBrandImg(bankerInfoRequest, bankerBrand.getId());
            boolean result = bankerBrandImgService.insertBatch(waitSaveList);
            return CommonResult.success();
        } catch (Exception e) {
            log.error("单笔新增品牌信息异常:{}", e);
        }
        return CommonResult.failed();
    }

    @Transactional
    public CommonResult singleUpdate(BankerBrandRequest request) {
        log.info("单笔修改品牌信息参数：{}", request);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            YxBankerBrand oldInfo = selectByPrimaryKey(request.getId());
            if (null == oldInfo) {
                return CommonResult.failed("找不到品牌信息");
            }
            Integer bankerId = bankerService.getUserInfo().getId();
            log.info("===当前编辑品牌用户id：" + bankerId);
            if (oldInfo.getReleased().equals(0) && bankerId.equals(request.getId())) {
                log.warn("===供应商品牌：" + request.getId() + ",暂未开发修改权限");
                return CommonResult.failed("暂未开发修改权限，请联系客户");
            }
            if (null != request.getBrandType()) {
                oldInfo.setBrandType(request.getBrandType());
            }
            if (StringUtils.isNotEmpty(request.getCategoryId())) {
                oldInfo.setCategoryId(request.getCategoryId());
            }
            if (StringUtils.isNotEmpty(request.getBrandName())) {
                oldInfo.setBrandName(request.getBrandName());
            }
            if (StringUtils.isNotEmpty(request.getBrandLimitStart())) {
                oldInfo.setBrandLimitStart(sdf.parse(request.getBrandLimitStart()));
            }
            if (StringUtils.isNotEmpty(request.getBrandLimitEnd())) {
                oldInfo.setBrandLimitEnd(sdf.parse(request.getBrandLimitEnd()));
            }
            if (StringUtils.isNotEmpty(request.getAuthorizationStartTime())) {
                oldInfo.setAuthorizationStartTime(sdf.parse(request.getAuthorizationStartTime()));
            }
            if (StringUtils.isNotEmpty(request.getAuthorizationEndTime())) {
                oldInfo.setAuthorizationEndTime(sdf.parse(request.getAuthorizationEndTime()));
            }
            if (null != request.getAuthorizationType()) {
                oldInfo.setAuthorizationType(request.getAuthorizationType());
            }
            oldInfo.setStatus(BrandStatusEnum.WAIT_CHECK.getCode());
            int count = bankerBrandMapper.updateByPrimaryKey(oldInfo);
            if (count <= 0) {
                return CommonResult.failed("修改失败");
            }

            if (null != oldInfo.getId()) {
                Example delExample = new Example(YxBankerBrandImg.class);
                delExample.createCriteria().andEqualTo("bankerBrandId", oldInfo.getId());
                bankerBrandImgService.deleteByExample(delExample);
            }

            BankerInfoRequest bankerInfoRequest = new BankerInfoRequest();
            BankerBrandRequest bankerBrandRequest = BankerBrandRequest.builder()
                    .registImgs(request.getRegistImgs())
                    .licensImgs(request.getLicensImgs())
                    .relImgs(request.getRelImgs())
                    .build();
            bankerInfoRequest.setBankerBrandRequest(bankerBrandRequest);
            List<YxBankerBrandImg> waitSaveList = buildYxBankerBrandImg(bankerInfoRequest, oldInfo.getId());
            boolean result = bankerBrandImgService.insertBatch(waitSaveList);
            return CommonResult.success();
        } catch (Exception e) {
            log.error("单笔修改品牌信息异常:{}", e);
        }
        return CommonResult.failed();
    }

    public CommonResult getDetail(Integer id) {
        YxBankerBrand bankerBrand = selectByPrimaryKey(id);
        if (null == bankerBrand) {
            return CommonResult.failed("找不到对应的品牌信息");
        }

        List<YxBankerBrandImg> imgs = getBankerBrandImgByBrandIdAndTypes(bankerBrand.getId(),
                Arrays.asList(BrandImgTypeEnum.REGIST.getCode(), BrandImgTypeEnum.LICENS.getCode(), BrandImgTypeEnum.REL.getCode()));
        List<BankerBrandImgResponse> imgResponseList = new ArrayList();
        imgs.stream().forEach(item -> {
            BankerBrandImgResponse response = new BankerBrandImgResponse();
            BeanUtils.copyProperties(item, response);
            imgResponseList.add(response);
        });

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> categoryIds = new ArrayList<>();
        if (!StringUtils.isEmpty(bankerBrand.getCategoryId())) {
            categoryIds = Arrays.asList(bankerBrand.getCategoryId().split(","));
        }
        BankerBrandListResponse response = BankerBrandListResponse.builder()
                .id(bankerBrand.getId())
                .brandType(bankerBrand.getBrandType())
                .brandName(bankerBrand.getBrandName())
                .registImgs(imgResponseList.stream().filter(s -> s.getType().equals(BrandImgTypeEnum.REGIST.getCode())).collect(Collectors.toList()))
                .licensImgs(imgResponseList.stream().filter(s -> s.getType().equals(BrandImgTypeEnum.LICENS.getCode())).collect(Collectors.toList()))
                .relImgs(imgResponseList.stream().filter(s -> s.getType().equals(BrandImgTypeEnum.REL.getCode())).collect(Collectors.toList()))
                .categoryIds(categoryIds.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList()))
                .release(bankerBrand.getReleased())
                .authorizationType(bankerBrand.getAuthorizationType())
                .build();
        if (null != bankerBrand.getBrandLimitStart()) {
            response.setBrandLimitStart(sdf.format(bankerBrand.getBrandLimitStart()));
        }
        if (null != bankerBrand.getBrandLimitEnd()) {
            response.setBrandLimitEnd(sdf.format(bankerBrand.getBrandLimitEnd()));
        }
        if (null != bankerBrand.getAuthorizationStartTime()) {
            response.setAuthorizationStartTime(sdf.format(bankerBrand.getAuthorizationStartTime()));
        }
        if (null != bankerBrand.getAuthorizationEndTime()) {
            response.setAuthorizationEndTime(sdf.format(bankerBrand.getAuthorizationEndTime()));
        }
        return CommonResult.success(response);
    }

    private List<YxBankerBrandImg> getBankerBrandImgByBrandIdAndTypes(Integer brandId, List<Integer> types) {
        Example example1 = new Example(YxBankerBrandImg.class);
        example1.createCriteria().andEqualTo("bankerBrandId", brandId)
                .andIn("type", types);
        List<YxBankerBrandImg> imgs = bankerBrandImgService.selectByExample(example1);
        return imgs;
    }

    public CommonPage<BankerBrandListResponse> list(BankerBrandListRequest request) {
        Integer bankerId = bankerService.getUserInfo().getId();
        Example example = new Example(YxBankerBrand.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("bankerId", bankerId);
        request.setBankerId(bankerId);
        if (null != request.getId()) {
            criteria.andEqualTo("id", request.getId());
        }
        if (null != request.getStartTime()) {
            criteria.andGreaterThanOrEqualTo("createTime", request.getStartTime());
        }
        if (null != request.getEndTime()) {
            criteria.andLessThanOrEqualTo("createTime", request.getEndTime());
        }
        if (null != request.getStatus()) {
            criteria.andEqualTo("status", request.getStatus());
        }
        if (null == request.getPageNum()) {
            request.setPageNum(1);
        }
        if (null == request.getPageSize()) {
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<YxBankerBrand> list = bankerBrandMapper.selectByExample(example);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf_createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<BankerBrandListResponse> resultList = new ArrayList<>();
        list.stream().forEach(obj -> {

            YxBankerSite site = bankerSiteService.selectByPrimaryKey(obj.getBankerSiteId());

            Example example0 = new Example(YxBankerBrandImg.class);
            example0.createCriteria().andEqualTo("bankerBrandId", obj.getId())
                    .andEqualTo("type", BrandImgTypeEnum.REGIST.getCode());
            List<YxBankerBrandImg> registImgs = bankerBrandImgService.selectByExample(example0);

            List<BankerBrandImgResponse> registImgResponseList = new ArrayList<>();
            registImgs.stream().forEach(item -> {
                BankerBrandImgResponse response = new BankerBrandImgResponse();
                BeanUtils.copyProperties(item, response);
                registImgResponseList.add(response);
            });

            Example example1 = new Example(YxBankerBrandImg.class);
            example1.createCriteria().andEqualTo("bankerBrandId", obj.getId())
                    .andEqualTo("type", BrandImgTypeEnum.LICENS.getCode());
            List<YxBankerBrandImg> licensImgs = bankerBrandImgService.selectByExample(example1);

            List<BankerBrandImgResponse> licensImgResponseList = new ArrayList<>();
            licensImgs.stream().forEach(item -> {
                BankerBrandImgResponse response = new BankerBrandImgResponse();
                BeanUtils.copyProperties(item, response);
                licensImgResponseList.add(response);
            });

            Example example2 = new Example(YxBankerBrandImg.class);
            example2.createCriteria().andEqualTo("bankerBrandId", obj.getId())
                    .andEqualTo("type", BrandImgTypeEnum.REL.getCode());
            List<YxBankerBrandImg> relImgs = bankerBrandImgService.selectByExample(example2);

            List<BankerBrandImgResponse> relImgResponseList = new ArrayList<>();
            relImgs.stream().forEach(item -> {
                BankerBrandImgResponse response = new BankerBrandImgResponse();
                BeanUtils.copyProperties(item, response);
                relImgResponseList.add(response);
            });

            String categoryName = "";
            if (null != obj.getCategoryId()) {
                Example example3 = new Example(YxProductCategory.class);
                example3.createCriteria().andIn("id", Arrays.asList(obj.getCategoryId().split(",")));
                List<YxProductCategory> categoryList = productCategoryMapper.selectByExample(example3);
                categoryName = categoryList.stream().map(p->p.getTitle()).collect(Collectors.joining(","));
            }

            BankerBrandListResponse response = BankerBrandListResponse.builder()
                    .id(obj.getId())
                    .brandType(obj.getBrandType())
                    .brandName(obj.getBrandName())
                    .createTime(sdf_createTime.format(obj.getCreateTime()))
                    .status(BrandStatusEnum.getMessageByCode(obj.getStatus()))
                    .siteName(null == site ? "" : site.getTitle())
                    .categoryName(categoryName)
                    .registImgs(registImgResponseList)
                    .licensImgs(licensImgResponseList)
                    .relImgs(relImgResponseList)
                    .release(obj.getReleased())
                    .offMsg(obj.getOffMsg())
                    .offTime(obj.getOffTime())
                    .checkMsg(obj.getCheckMsg())
                    .build();
            if (null != obj.getBrandLimitStart()) {
                response.setBrandLimitStart(sdf.format(obj.getBrandLimitStart()));
            }
            if (null != obj.getBrandLimitEnd()) {
                response.setBrandLimitEnd(sdf.format(obj.getBrandLimitEnd()));
            }
            resultList.add(response);
        });
        CommonPage commonPage = CommonPage.restPage(list);
        commonPage.setList(resultList);
        return commonPage;
    }

    /**
     * 释放
     * @param request
     * @return
     */
    public CommonResult release(BankerUpdateReleaseRequest request) {
        YxBankerBrand brand = selectByPrimaryKey(request.getId());
        if (null == brand) {
            return CommonResult.failed("找不到品牌信息");
        }
        brand.setReleased(request.getStatus());
        int count = updateByPrimaryKey(brand);
        if (count > 0) {
            return CommonResult.success("释放成功");
        }
        return CommonResult.failed("释放失败");
    }

    @Transactional
    public CommonResult brandPutOn(BankerUpdatePutOnRequest request) {
        YxBankerBrand brand = selectByPrimaryKey(request.getId());
        if (null == brand) {
            return CommonResult.failed("找不到品牌信息");
        }
        if (!BrandStatusEnum.PASS.getCode().equals(brand.getStatus())) {
            return CommonResult.failed("品牌未审核通过不能上架/下架");
        }
        brand.setPutOn(request.getStatus());
        if (0 == request.getStatus()) {
            brand.setOffMsg(request.getMsg());
            brand.setOffTime(new Date());
        }else {
            brand.setOffMsg(null);
            brand.setOffTime(null);
        }
        int count = updateByPrimaryKey(brand);
        if (count > 0) {
            //上下架品牌下的商品信息
            bankerProductService.updateStatusByBrandId(request.getId(), request.getStatus() == 1 ? 1 : 2);
            return CommonResult.success("操作成功");
        }
        return CommonResult.failed("操作失败");
    }

    public CommonResult<BankerInfoResponse> getBankerDetailInfo() {
        YxBanker banker = bankerService.getUserInfo();
        if (null == banker) {
            return CommonResult.failed("找不到供应商信息");
        }
        YxBankerInfo bankerInfo = bankerInfoService.selectByBankerId(banker.getId());
        if (null == bankerInfo) {
            bankerInfo = new YxBankerInfo();
        }
        YxBankerSite bankerSite = bankerSiteService.selectByBankerId(banker.getId());
        if (null == bankerSite) {
            bankerSite = new YxBankerSite();
        }

        //用来判断是否是历史数据
        boolean isOldInfo = false;// true-历史数据  false-新数据
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date upLineTimeDate = sdf.parse("2021-04-13 00:00:00");
            if (banker.getCreateTime().before(upLineTimeDate) && historyOff) {
                isOldInfo = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        BankerInfoResponse response = BankerInfoResponse.builder()
                .infoId(bankerInfo.getId())
                .companyName(bankerInfo.getCompanyName())
                .companyAddress(bankerInfo.getCompanyAddress())
                .companyTel(bankerInfo.getCompanyTel())
                .businessLicense(bankerInfo.getBusinessLicense())
                .businessLicenseImg(bankerInfo.getBusinessLicenseImg())
                .businessLimitStart(null != bankerInfo.getBusinessLimitStart() ? sdf.format(bankerInfo.getBusinessLimitStart()) : "")
                .businessLimitEnd(null != bankerInfo.getBusinessLimitEnd() ? sdf.format(bankerInfo.getBusinessLimitEnd()) : "")
                .forver(bankerInfo.getForver())
                .hostName(bankerInfo.getHostName())
                .idCard(bankerInfo.getIdCard())
                .cardImgFront(bankerInfo.getCardImgFront())
                .cardImgBehind(bankerInfo.getCardImgBehind())
                .creditCardNumbers(bankerInfo.getCreditCardNumbers())
                .bankHouse(bankerInfo.getBankHouse())
                .siteId(bankerSite.getId())
                .title(bankerSite.getTitle())
                .longTitle(bankerSite.getLongTitle())
                .brandStory(bankerSite.getBrandStory())
                .logo(bankerSite.getLogo())
                .bgImg(bankerSite.getBgImg())
                .shareImg(bankerSite.getShareImg())
                .shareCopywrite(bankerSite.getShareCopywrite())
                .build();

        YxBankerBrand bankerBrand = selectByBankerIdAndFistTime(banker.getId(), 1);
        if (isOldInfo || null == bankerBrand) {
            response.setBankerBrandResponse(BankerBrandResponse.builder().build());
            return CommonResult.success(response);
        }
        List<String> categoryIds = new ArrayList<>();
        if (null != bankerBrand.getCategoryId()) {
            categoryIds = Arrays.asList(bankerBrand.getCategoryId().split(","));
        }
        List<YxBankerBrandImg> imgs = getBankerBrandImgByBrandIdAndTypes(bankerBrand.getId(),
                Arrays.asList(BrandImgTypeEnum.REGIST.getCode(), BrandImgTypeEnum.LICENS.getCode(), BrandImgTypeEnum.REL.getCode()));
        List<BankerBrandImgResponse> imgResponseList = new ArrayList<>();
        imgs.stream().forEach(item -> {
            BankerBrandImgResponse imgResponse = new BankerBrandImgResponse();
            BeanUtils.copyProperties(item, imgResponse);
            imgResponseList.add(imgResponse);
        });
        BankerBrandResponse brandResponse = BankerBrandResponse.builder()
                .brandId(bankerBrand.getId())
                .brandType(bankerBrand.getBrandType())
                .categoryIds(categoryIds.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList()))
                .brandName(bankerBrand.getBrandName())
                .registImgs(imgResponseList.stream().filter(s -> s.getType().equals(BrandImgTypeEnum.REGIST.getCode())).collect(Collectors.toList()))
                .licensImgs(imgResponseList.stream().filter(s -> s.getType().equals(BrandImgTypeEnum.LICENS.getCode())).collect(Collectors.toList()))
                .relImgs(imgResponseList.stream().filter(s -> s.getType().equals(BrandImgTypeEnum.REL.getCode())).collect(Collectors.toList()))
                .build();
        if (null != bankerBrand.getBrandLimitStart()) {
            brandResponse.setBrandLimitStart(sdf.format(bankerBrand.getBrandLimitStart()));
        }
        if (null != bankerBrand.getBrandLimitEnd()) {
            brandResponse.setBrandLimitEnd(sdf.format(bankerBrand.getBrandLimitEnd()));
        }
        response.setBankerBrandResponse(brandResponse);
        return CommonResult.success(response);
    }

    @Transactional
    public boolean buildOldData() {
        List<WaitBuildOldDto> list =  bankerBrandMapper.selectWaitBuildOldData();

        List<YxBankerBrand> waitSaveObjs = new LinkedList<>();
        List<YxBankerBrandImg> waitSaveImgObjs = new LinkedList<>();
        list.stream().forEach(obj -> {
            YxBankerBrand bankerBrand = YxBankerBrand.builder()
                    .brandType(obj.getBankerType())
                    .brandName(obj.getBankerName())
                    .createTime(obj.getCreateTime())
                    .bankerSiteId(obj.getBankerSiteId())
                    .bankerId(obj.getBankerId())
                    .status(BrandStatusEnum.PASS.getCode())
                    .released(1)
                    .firstTime(1)
                    .putOn(1)
                    .build();

            //处理品牌授权书
            String brandLicensing = obj.getBrandLicensing();
            if (StringUtils.isNotEmpty(brandLicensing)) {
                waitSaveImgObjs.addAll(handleImg(brandLicensing, BrandImgTypeEnum.LICENS.getCode(), obj.getBankerId(), bankerBrand.getId()));
            }
            //处理商标注册证
            String registerCertificate = obj.getRegisterCertificate();
            if (StringUtils.isNotEmpty(registerCertificate)) {
                waitSaveImgObjs.addAll(handleImg(registerCertificate, BrandImgTypeEnum.REGIST.getCode(), obj.getBankerId(), bankerBrand.getId()));
            }
            waitSaveObjs.add(bankerBrand);
        });
        insertBatch(waitSaveObjs);
        waitSaveImgObjs.stream().forEach(s2 -> {
            waitSaveObjs.stream().forEach(s1 -> {
                if (s2.getBankerId().equals(s1.getBankerId())) {
                    s2.setBankerBrandId(s1.getId());
                }
            });
        });
        bankerBrandImgService.insertBatch(waitSaveImgObjs);
        return true;
    }

    private List<YxBankerBrandImg> handleImg(String imgs, Integer type, Integer bankerId, Integer bankerBrandId) {
        List<String> imgList = Arrays.asList(imgs.split(","));
        List<YxBankerBrandImg> returnList = new LinkedList<>();
        for (int i = 0; i < imgList.size(); i++) {
            YxBankerBrandImg bean = YxBankerBrandImg.builder()
                    .type(type)
                    .bankerBrandId(bankerBrandId)
                    .imgUrl(imgList.get(i))
                    .sort(i)
                    .createTime(new Date())
                    .bankerId(bankerId)
                    .build();
            returnList.add(bean);
        }
        return returnList;
    }

    public CommonResult queryAllBrandList() {
        YxBanker banker = bankerService.getUserInfo();
        List<YxBankerBrand> brandList = selectByBankerIdAndStatus(banker.getId(), BrandStatusEnum.PASS.getCode());
        List<BankerBrandSelectorResponse> returnList = new ArrayList<>();
        brandList.stream().forEach(s -> {
            BankerBrandSelectorResponse response = BankerBrandSelectorResponse.builder()
                    .id(s.getId())
                    .brandName(s.getBrandName())
                    .build();
            returnList.add(response);
        });
        return CommonResult.success(returnList);
    }

    public List<YxBankerBrand> selectByBankerIdAndStatus(Integer bankerId, Integer status) {
        Example example = new Example(YxBankerBrand.class);
        example.createCriteria().andEqualTo("bankerId", bankerId).andEqualTo("status", status);
        List<YxBankerBrand> brandInfos = selectByExample(example);
        return brandInfos;
    }

    public CommonResult updateBrandName(BrandUpdateNameRequest request) {
        YxBankerBrand brand = YxBankerBrand.builder()
                .id(request.getId())
                .brandName(request.getName())
                .build();

        int count = updateByPrimaryKeySelective(brand);
        return count > 0 ? CommonResult.success("修改成功") : CommonResult.failed("修改失败");
    }

    /**
     * 根据店铺id下架品牌信息
     * @param siteId 店铺id
     * @param status 下架状态
     * @return
     */
    public boolean brandPutOnBySiteId(Integer siteId, Integer status) {
        List<YxBankerBrand> brands = selectBySiteId(siteId);
        if (null == brands) {
            return true;
        }
        brands.stream().forEach(s -> {
            s.setPutOn(status);
        });
        updateBatchByPrimaryKeySelective(brands);
        return true;
    }

    /**
     * 根据店铺id查询其下的所有品牌信息
     * @param siteId
     * @return
     */
    private List<YxBankerBrand> selectBySiteId(Integer siteId) {
        Example example = new Example(YxBankerBrand.class);
        example.createCriteria().andEqualTo("bankerSiteId", siteId);
        List<YxBankerBrand> brands = selectByExample(example);
        return brands;
    }

    public CommonPage<BankerBrandVO> selectList(BankerBrandRequest bankerBrandRequest) {
        PageHelper.startPage(bankerBrandRequest.getPageNum(), bankerBrandRequest.getPageSize());
        List<BankerBrandVO> pageList = bankerBrandMapper.selectList(bankerBrandRequest);
        for (int i = 0; i<pageList.size();i++) {
            BankerBrandVO cateId = pageList.get(i);
            if (com.alibaba.excel.util.StringUtils.isEmpty(cateId.getCategoryId())) {
                continue;
            }
            List<String> paramList = Arrays.asList(cateId.getCategoryId().split(","));
            List<Integer> categoryIds = paramList.stream().map(Integer::parseInt).collect(Collectors.toList());
            Example example = new Example(YxProductCategory.class);
            example.createCriteria().andIn("id", categoryIds);
            List<YxProductCategory> categoryList = productCategoryMapper.selectByExample(example);

            String titles = categoryList.stream().map(p->p.getTitle()).collect(Collectors.joining(","));

            cateId.setCategoryTitles(titles);
        }
        pageList.stream().forEach(obj -> {
            if (null == obj.getBrandType()) {
                obj.setBrandType(obj.getBankerType());
            }
            Example example = new Example(YxBankerBrandImg.class);
            example.createCriteria().andEqualTo("bankerBrandId", obj.getId());
            List<YxBankerBrandImg> bankerBrandImgs = bankerBrandImgMapper.selectByExample(example);

//            List<YxBankerBrandImg> imgList = bankerBrandDao.selectAllImgList(obj.getId());
            if (CollectionUtils.isEmpty(bankerBrandImgs)) {
                bankerBrandImgs = new ArrayList<>();

                Example example1 = new Example(YxBankerInfo.class);
                example1.createCriteria().andEqualTo("bankerId", obj.getBankerId());
                YxBankerInfo bankerInfo = bankerInfoMapper.selectOneByExample(example1);

//                YxBankerInfo bankerInfo = bankerInfoService.getBankerInfoStatus(obj.getBankerId());

                List<String> list1 = new ArrayList<>();
                if (!com.alibaba.excel.util.StringUtils.isEmpty(bankerInfo.getRegisterCertificate())) {
                    list1 = Arrays.asList(bankerInfo.getRegisterCertificate().split(","));
                }
                for (String imgUrl : list1) {
                    YxBankerBrandImg type1Img = new YxBankerBrandImg();
                    type1Img.setType(1);
                    type1Img.setImgUrl(imgUrl);
                    bankerBrandImgs.add(type1Img);
                }

                List<String> list2 = new ArrayList<>();
                if (!com.alibaba.excel.util.StringUtils.isEmpty(bankerInfo.getBrandLicensing())) {
                    list2 = Arrays.asList(bankerInfo.getBrandLicensing().split(","));
                }
                for (String imgUrl : list2) {
                    YxBankerBrandImg type2Img = new YxBankerBrandImg();
                    type2Img.setType(2);
                    type2Img.setImgUrl(imgUrl);
                    bankerBrandImgs.add(type2Img);
                }
            }
            List<BankerBrandImgVO> bankerBrandImgVOList = new ArrayList<>();
            bankerBrandImgs.stream().forEach(item -> {
                BankerBrandImgVO vo = new BankerBrandImgVO();
                BeanUtils.copyProperties(item, vo);
                bankerBrandImgVOList.add(vo);
            });
            obj.setBankerBrandImgs(bankerBrandImgVOList);
        });

        return CommonPage.restPage(pageList);
    }

    public CommonResult queryBankerBrandListByBankerId(Integer bankerId) {
        Example example = new Example(YxBankerBrand.class);
        example.createCriteria().andEqualTo("bankerId", bankerId);
        example.selectProperties("id", "brandName");
        List<YxBankerBrand> bankerBrandList = bankerBrandMapper.selectByExample(example);
        return CommonResult.success(bankerBrandList);
    }
}
